<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 分类树形列表 -->
      <el-col :span="6" :xs="24">
        <el-card shadow="never" class="tree-card">
          <div slot="header" class="clearfix">
            <span>题目分类</span>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              icon="el-icon-refresh"
              @click="getCategoryTree"
            >刷新</el-button>
          </div>
          <div class="head-container">
            <el-input
              v-model="treeFilterText"
              placeholder="请输入分类名称"
              clearable
              size="small"
              prefix-icon="el-icon-search"
            />
          </div>
          <el-tree
            ref="categoryTree"
            :data="categoryTreeData"
            :props="treeProps"
            :expand-on-click-node="false"
            :filter-node-method="filterTreeNode"
            node-key="id"
            highlight-current
            @node-click="handleTreeNodeClick"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span>{{ node.label }}</span>
              <span>
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-plus"
                  @click.stop="() => handleAdd(data)"
                  v-hasPermi="['question.js:category:add']"
                />
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-edit"
                  @click.stop="() => handleUpdate(data)"
                  v-hasPermi="['question.js:category:edit']"
                />
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-delete"
                  @click.stop="() => handleDelete(data)"
                  v-hasPermi="['question.js:category:delete']"
                />
              </span>
            </span>
          </el-tree>
        </el-card>
      </el-col>

      <!-- 知识点分页列表 -->
      <el-col :span="18" :xs="24">
        <el-card shadow="never">
          <!-- 搜索区域 -->
          <div class="search-container">
            <div class="search-header">
              <el-button
                type="text"
                :icon="showSearch ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
                @click="toggleSearch"
              >
                {{ showSearch ? '隐藏搜索' : '显示搜索' }}
              </el-button>
              <el-button
                type="text"
                icon="el-icon-setting"
                @click="showColumnDialog = true"
              >
                列设置
              </el-button>
            </div>

            <el-collapse-transition>
              <el-form
                v-show="showSearch"
                ref="queryForm"
                :model="queryParams"
                :inline="true"
                label-width="80px"
              >
                <el-form-item label="上级分类" prop="parentId">
                  <el-cascader
                    v-model="queryParams.parentId"
                    :options="categoryTreeData"
                    :props="cascaderProps"
                    clearable
                    style="width: 240px"
                    placeholder="请选择上级分类"
                  />
                </el-form-item>
                <el-form-item label="知识点名称" prop="name">
                  <el-input
                    v-model="queryParams.name"
                    placeholder="请输入知识点名称"
                    clearable
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                  <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-collapse-transition>
          </div>

          <!-- 操作按钮 -->
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                icon="el-icon-plus"
                @click="handleAdd"
                v-hasPermi="['question.js:category:add']"
              >新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="success"
                icon="el-icon-edit"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['question.js:category:edit']"
              >修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                icon="el-icon-delete"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['question.js:category:delete']"
              >删除</el-button>
            </el-col>
          </el-row>

          <!-- 表格数据 -->
          <el-table
            v-loading="loading"
            :data="knowledgeList"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              v-if="columns[0].visible"
              type="selection"
              width="55"
              align="center"
            />
            <el-table-column
              v-if="columns[1].visible"
              label="ID"
              prop="id"
              width="200"
              align="center"
            />
            <el-table-column
              v-if="columns[2].visible"
              label="知识点名称"
              prop="name"
              align="center"
            />
            <el-table-column
              v-if="columns[3].visible"
              label="上级分类"
              prop="parentName"
              align="center"
            />
            <el-table-column
              v-if="columns[4].visible"
              label="排序"
              prop="sort"
              align="center"
            />
            <el-table-column
              v-if="columns[5].visible"
              label="操作"
              align="center"
              width="180"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['question.js:category:edit']"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['question.js:category:delete']"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getKnowledgeList"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加/修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="上级分类" prop="parentId">
          <el-cascader
            v-model="form.parentId"
            :options="categoryTreeDataDialog"
            :props="cascaderProps"
            clearable
            style="width: 100%"
            placeholder="请选择上级分类"
          />
        </el-form-item>
        <el-form-item label="类型" prop="isKnowledge">
          <el-radio-group v-model="form.isKnowledge">
            <el-radio :label="1" >知识点</el-radio>
            <el-radio :label="0">分类</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入编码" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" controls-position="right" :min="0" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 列设置对话框 -->
    <el-dialog title="列设置" :visible.sync="showColumnDialog" width="500px" append-to-body>
      <el-form>
        <el-form-item>
          <el-checkbox-group v-model="columnOptions">
            <el-checkbox
              v-for="item in columns"
              :key="item.key"
              :label="item.key"
            >{{item.label}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveColumnSettings">确 定</el-button>
        <el-button @click="showColumnDialog = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCategoryTree,
  pageKnowledge,
  addCategory,
  updateCategory,
  delCategory,
  getCategory
} from "@/api/question2/category";

export default {
  name: "QuestionCategory",
  data() {
    return {
      // 分类树相关
      treeFilterText: '',
      categoryTreeData: [],
      categoryTreeDataDialog: [],
      treeProps: {
        children: 'children',
        label: 'name'
      },
      cascaderProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        checkStrictly: true,
        emitPath: false
      },

      // 知识点列表相关
      knowledgeList: [],
      total: 0,
      loading: true,
      showSearch: true,
      showColumnDialog: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        parentId: null,
        name: undefined,
        isKnowledge: 1
      },

      // 表单相关
      open: false,
      title: '',
      form: {
        isKnowledge: 1
      },
      rules: {
        parentId: [
          { required: true, message: "上级分类不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        code: [
          { required: true, message: "编码不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ]
      },

      // 列设置相关
      columns: [
        { key: 'selection', label: '选择列', visible: true },
        { key: 'id', label: 'ID', visible: true },
        { key: 'name', label: '知识点名称', visible: true },
        { key: 'parentName', label: '上级分类', visible: true },
        { key: 'sort', label: '排序', visible: true },
        { key: 'action', label: '操作', visible: true }
      ],

      // 选中相关
      ids: [],
      single: true,
      multiple: true
    };
  },
  computed: {
    columnOptions: {
      get() {
        return this.columns.filter(item => item.visible).map(item => item.key);
      },
      set(value) {
        this.columns.forEach(item => {
          item.visible = value.includes(item.key);
        });
      }
    }
  },
  watch: {
    treeFilterText(val) {
      this.$refs.categoryTree.filter(val);
    }
  },
  created() {
    this.getCategoryTree();
    this.getKnowledgeList();
    this.loadColumnSettings();
  },
  methods: {
    // 获取分类树
    getCategoryTree() {
      getCategoryTree().then(response => {
        console.log('categoryTreeData', response.data)
        this.categoryTreeData = response.data;
        // 深拷贝
        this.categoryTreeDataDialog = [{id: 0, name: '根节点'}]
        response.data.forEach(item => {
          this.categoryTreeDataDialog.push({
            id: item.id,
            name: item.name,
            parentId: item.parentId,
            children: item.children
          })
        })
      });
    },

    // 获取知识点列表
    getKnowledgeList() {
      this.loading = true;
      pageKnowledge(this.queryParams).then(response => {
        this.knowledgeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 树节点过滤
    filterTreeNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },

    // 树节点点击
    handleTreeNodeClick(data) {
      this.queryParams.parentId = data.id;
      this.getKnowledgeList();
    },

    // 其他方法保持不变...
    toggleSearch() {
      this.showSearch = !this.showSearch;
    },

    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getKnowledgeList();
    },

    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.parentId = null;
      this.handleQuery();
    },

    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    handleAdd(data) {
      this.reset();
      this.open = true;
      this.title = "添加" + (data ? "子分类" : "分类");
      if (data) {
        this.form.parentId = data.id;
      }
    },

    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      getCategory(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改分类";
      });
    },

    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCategory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getCategoryTree();
              this.getKnowledgeList();
            });
          } else {
            addCategory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getCategoryTree();
              this.getKnowledgeList();
            });
          }
        }
      });
    },

    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的数据项？').then(() => {
        return delCategory(ids);
      }).then(() => {
        this.getCategoryTree();
        this.getKnowledgeList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    loadColumnSettings() {
      const savedSettings = localStorage.getItem('questionCategoryColumns');
      if (savedSettings) {
        try {
          const settings = JSON.parse(savedSettings);
          this.columns.forEach(col => {
            if (settings[col.key] !== undefined) {
              col.visible = settings[col.key];
            }
          });
        } catch (e) {
          console.error('加载列设置失败:', e);
        }
      }
    },

    saveColumnSettings() {
      const settings = {};
      this.columns.forEach(col => {
        settings[col.key] = col.visible;
      });
      localStorage.setItem('questionCategoryColumns', JSON.stringify(settings));
      this.showColumnDialog = false;
      this.$modal.msgSuccess("列设置保存成功");
    },

    reset() {
      this.form = {
        id: undefined,
        parentId: null,
        name: undefined,
        code: undefined,
        isKnowledge: 0,
        sort: 0
      };
      this.resetForm("form");
    },

    cancel() {
      this.open = false;
      this.reset();
    }
  }
};
</script>

<style scoped>
.tree-card {
  height: calc(100vh - 120px);
  overflow-y: auto;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
